package io.github.cameradddd.controller;

import java.util.List;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.github.cameradddd.dao.RecordDAO;
import io.github.cameradddd.entity.AccountRecord;

@RestController
public class AccountController {
    /**
     * 查看余额请求
     * 
     * @return
     */
    @PostMapping("/api/checkAccount")
    public ResponseEntity<?> checkAccount() {
        String balance = ((Double) RecordDAO.calculateAmount()).toString();
        return ResponseEntity.ok(Map.of(
                "code", 200,
                "success", true,
                "data", Map.of("balance", balance)));
    }

    /**
     * 处理收入请求
     * 
     * @param request
     * @return
     */
    @PostMapping("/api/income")
    public ResponseEntity<?> income(@RequestBody Map<String, String> request) {
        String amount = request.get("amount");
        String remark = request.get("remark");
        // 防止remark为空导致读取csv文件出错
        if (remark == null || remark == "")
            remark = "无";

        RecordDAO.createRecord("收入", Double.parseDouble(amount), remark);
        Map<String, Object> response = Map.of(
                "code", 200,
                "success", true,
                "data", Map.of("amount", amount.toString()));
        return ResponseEntity.ok(response);
    }

    /**
     * 处理支出请求
     * 
     * @param request
     * @return
     */
    @PostMapping("/api/outcome")
    public ResponseEntity<?> outcome(@RequestBody Map<String, String> request) {
        String amount = request.get("amount");
        String remark = request.get("remark");
        // 防止remark为空导致读取csv文件出错
        if (remark == null || remark == "")
            remark = "无";

        RecordDAO.createRecord("支出", Double.parseDouble(amount), remark);

        Map<String, Object> response = Map.of(
                "code", 200,
                "success", true,
                "data", Map.of("amount", amount.toString()));
        return ResponseEntity.ok(response);
    }

    /**
     * 发送所有账目
     * 
     * @return
     */
    @GetMapping("/api/allRecords")
    public ResponseEntity<?> getAllRecords() {
        List<AccountRecord> records = RecordDAO.findAll();
        Map<String, Object> response = Map.of(
                "code", 200,
                "success", true,
                "data", records);
        return ResponseEntity.ok(response);
    }

    /**
     * 处理删除账目请求
     * 
     * @return
     */
    @PostMapping("/api/remove")
    public ResponseEntity<?> remove(@RequestBody Map<String, Object> request) {
        Object idObj = request.get("id");
        // 解析id字段
        Integer id = null;
        if (idObj instanceof Number) {
            id = ((Number) idObj).intValue();
        } else if (idObj instanceof String) {
            try {
                id = Integer.parseInt((String) idObj);
            } catch (NumberFormatException e) {
                System.err.println("id类型错误");
            }
        }
        boolean deleted=true;//TODO
        String errorMsg = null;

        if (id == null) {// 如果POST请求hashCode为空,默认删除最后的账目

            RecordDAO.deleteRecord();

            if (!deleted) {
                errorMsg = "No records exist";
            }

        } else {
            RecordDAO.deleteRecord(id);
            if (!deleted) {
                errorMsg = "Record not found";
            }
        }

        // 删除失败,可能是id不存在
        if (!deleted) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                    "code", 400,
                    "success", false,
                    "message", errorMsg));
        }

        return ResponseEntity.ok(Map.of(
                "code", 200,
                "success", true));
    }

    /**
     * 处理批量删除请求
     * 
     * @param request
     * @return
     */
    @PostMapping("/api/removeMultiple")
    public ResponseEntity<?> removeMultiple(@RequestBody Map<String, List<Integer>> request) {
        List<Integer> idList = request.get("idList");
        boolean deleted = true;//TODO
        RecordDAO.deleteRecord(idList);
        if (!deleted) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                    "code", 400,
                    "success", false,
                    "message", "Some records not found or failed to delete"));
        }
        return ResponseEntity.ok(Map.of(
                "code", 200,
                "success", true));
    }

    /**
     * 处理修改账目请求
     * 
     * @param request
     * @return
     */
    @PostMapping("/api/edit")
    public ResponseEntity<?> editRecord(@RequestBody Map<String, Object> request) {
        Integer id = null;
        // 解析id
        Object idObj = request.get("id");
        if (idObj instanceof Number) {
            id = ((Number) idObj).intValue();
        } else if (idObj instanceof String) {
            try {
                id = Integer.parseInt((String) idObj);
            } catch (NumberFormatException e) {
                System.err.println("id错误");
            }
        }

        // 解析amount
        Double amount = null;
        if (request.get("amount") instanceof Number) {
            amount = ((Number) request.get("amount")).doubleValue();
        } else if (request.get("amount") instanceof String) {
            try {
                amount = Double.parseDouble((String) request.get("amount"));
            } catch (NumberFormatException e) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                        "code", 400,
                        "success", false,
                        "message", "Invalid amount format"));
            }
        }

        // 解析remark
        String remark = null;
        if (request.get("remark") != null) {
            remark = request.get("remark").toString();
        }

        if (id == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                    "code", 400,
                    "success", false,
                    "message", "Missing required id field"));
        }

        // 允许 amount 或 remark 有一项为 null
        if (amount == null && remark == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                    "code", 400,
                    "success", false,
                    "message", "At least one of amount or remark must be provided"));
        }

        // 有一项为空时
        boolean updated = true;
        if (amount == null && remark != null) {
            RecordDAO.editRecord(id, remark);
        }
        if (amount != null && remark == null) {
            RecordDAO.editRecord(id, amount);
        }
        // 两项均不为空时
        if (amount != null && remark != null) {
            RecordDAO.editRecord(id, amount, remark);
        }

        if (!updated) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                    "code", 400,
                    "success", false,
                    "message", "Record not found or failed to update"));
        }

        return ResponseEntity.ok(Map.of(
                "code", 200,
                "success", true));
    }

}
